<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form ref="form" size="large" autocomplete="off" :model="registerData" :rules="rules">
        <el-form-item>
          <h1>咨询预约管理登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-select placeholder="请选择角色" v-model="registerData.role">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="咨询师" value="consultant"></el-option>
            <el-option label="用户" value="user"></el-option>
          </el-select>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">
            登录
          </el-button>
          <el-button type="text" @click="registerDialogVisible = true">注册</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!-- 注册对话框 -->
    <el-dialog v-model="registerDialogVisible" title="注册新账号" width="400px">
      <el-form :model="registerForm" label-width="80px">
        <el-form-item label="角色">
          <el-select v-model="registerForm.role" placeholder="请选择角色">
            <el-option label="咨询师" value="consultant"></el-option>
            <el-option label="用户" value="user"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="registerForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="registerForm.age" type="number"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="registerForm.gender" placeholder="请选择性别">
            <el-option label="男" value="Male"></el-option>
            <el-option label="女" value="Female"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="registerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onRegister">注册</el-button>
      </template>
    </el-dialog>
  </el-row>
</template>

<script setup>
import { Lock, User } from "@element-plus/icons-vue";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { userLogin, adminLogin, consultantLogin } from "@/api/login";
import axios from 'axios';

const router = useRouter();
const form = ref(null);
const registerData = ref({
  username: '',
  password: '',
  role: ''
});

const registerDialogVisible = ref(false);
const registerForm = ref({
  role: '',
  username: '',
  password: '',
  age: '',
  gender: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 16, message: '长度为 1-16 位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 30, message: '长度为 1-30 位', trigger: 'blur' },
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' },
  ]
};

const login = () => {
  form.value.validate((valid) => {
    if (valid) {
      const obj = {
        params: {
          username: registerData.value.username,
          password: registerData.value.password
        }
      };
      let loginApi;
      if (registerData.value.role === 'admin') {
        loginApi = adminLogin;
      } else if (registerData.value.role === 'consultant') {
        loginApi = consultantLogin;
      } else if (registerData.value.role === 'user') {
        loginApi = userLogin;
      }
      // 发送请求
      loginApi(obj).then(res => {
        if (res.success) {
          if (registerData.value.role === 'admin') {
            router.push({ name: "adminHome" });
          } else if (registerData.value.role === 'consultant') {
            router.push({ name: "consultantHome" });
          } else if (registerData.value.role === 'user') {
            router.push({ name: "userHome" });
          }
          ElMessage.success(res.message ? res.message : "登录成功");
        } else {
          ElMessage.error(res.message);
        }
      });
    }
  });
};

const onRegister = async () => {
  if (!registerForm.value.role || !registerForm.value.username || !registerForm.value.password || !registerForm.value.age || !registerForm.value.gender) {
    ElMessage.error('请填写完整信息');
    return;
  }
  const params = new URLSearchParams();
  params.append('username', registerForm.value.username);
  params.append('password', registerForm.value.password);
  params.append('age', registerForm.value.age);
  params.append('gender', registerForm.value.gender);
  let url = '';
  if (registerForm.value.role === 'consultant') {
    url = '/api/consultant/insert.do';
  } else if (registerForm.value.role === 'user') {
    url = '/api/user/insert.do';
  } else {
    ElMessage.error('请选择正确的角色');
    return;
  }
  try {
    const res = await axios.post(url, params, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    if (res.data.code === 200) {
      ElMessage.success('注册成功，请登录');
      registerDialogVisible.value = false;
      // 清空注册表单
      registerForm.value = { role: '', username: '', password: '', age: '', gender: '' };
    } else {
      ElMessage.error(res.data.message || '注册失败');
    }
  } catch (e) {
    ElMessage.error('请求失败');
  }
};
</script>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: no-repeat 60% center / 240px auto,
    url('@/assets/login-background.jpg') no-repeat center / cover;
    border-radius: 0 10px 10px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }
  }
}
</style>